import { App } from 'vue'
import { defineComponent, reactive, watch, inject, getCurrentInstance } from "vue"
import { getComponent } from '../_util/props-util';
import Star from './Star'
import Icon from '../icon'

const Rate = defineComponent({
  name: 'x-rate',
  props: {
    prefixCls: { default: 'x-rate' },
    value: Number,
    character: String,
    count: { default: 5 },
    color: String,
    allowHalf: Boolean,
    disabled: Boolean
  },
  emits: ['update:value', 'change', 'hoverChange'],
  setup(props, { emit }) {
    const { proxy: self } = getCurrentInstance()

    const state = reactive({
      value: props.value,
      hoverValue: null
    })
    watch(() => props.value, val => {
      state.value = val
    })

    function getStarValue(e: MouseEvent, i: number) {
      if (props.allowHalf) {
        return e.offsetX > (e.target as HTMLElement).offsetWidth / 2
          ? i + 1
          : i + .5
      } else {
        return i + 1
      }
    }

    function onClick(e, i) {
      state.value = getStarValue(e, i)
    }
    function onHover(e: MouseEvent, i) {
      
      state.hoverValue = getStarValue(e, i)
      emit('hoverChange', state.hoverValue)
    }
    function onMouseleave() {
      state.hoverValue = null
    }

    return () => {
      const { prefixCls, disabled } = props
      const ratePorps = {
        class: prefixCls,
        role: 'radiogroup',
        tabindex: 0,
        onMouseleave: disabled ? null : onMouseleave
      }
      const itemProps = {
        prefixCls: `${prefixCls}_star`,
        value: state.hoverValue || state.value,
        character: getComponent(self, 'character') || <Icon type="ziyuan"></Icon>,
        allowHalf: props.allowHalf,
        disabled: props.disabled,
        count: props.count,
        color: props.color,
        onClick,
        onHover
      }
      const children = Array.from(Array(props.count), (_, i) => {
        return <Star {...itemProps} index={i}></Star>
      })

      return (
        <div {...ratePorps}>
          {children}
        </div>
      )
    }
  }
})

Rate.install = (app: App) => {
  app.component(Rate.name, Rate)
}

export default Rate